package org.jeecg.modules.sggg.controller;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.sggg.entity.SgBlutdruckRecord;
import org.jeecg.modules.sggg.entity.SgHealthRecord;
import org.jeecg.modules.sggg.entity.SgMember;
import org.jeecg.modules.sggg.service.ISgHealthRecordService;
import org.jeecg.modules.sggg.service.ISgMemberService;
import org.jeecg.modules.system.controller.SysRoleController;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

/**
 * @Description: 体质监测表
 * @Author: jeecg-boot
 * @Date: 2022-10-17
 * @Version: V1.0
 */
@Api(tags = "体质监测表")
@RestController
@RequestMapping("/sggg/sgHealthRecord")
@Slf4j
public class SgHealthRecordController extends JeecgController<SgHealthRecord, ISgHealthRecordService> {
    @Autowired
    private ISgHealthRecordService sgHealthRecordService;

    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private SysRoleController sysRoleController;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDepartService sysDepartController;


    @ApiOperation(value = "体质监测表-分页列表查询", notes = "体质监测表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SgHealthRecord>> queryPageList(SgHealthRecord sgHealthRecord,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysRole> roles = sysRoleController.getUserRole(sysUser.getId()).getResult();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
//                queryWrapper.eq("doctor_id", sysUser1.getId().toString());
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgHealthRecord.setResponsibleAgencies(responsibleAgencies);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgHealthRecord.setResponsibleAgencies(responsibleAgencies);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }

        Page<SgHealthRecord> page = new Page<>(pageNo, pageSize);
        IPage<SgHealthRecord> pageList = sgHealthRecordService.queryList(page, sysUser.getId(), sgHealthRecord, roles.get(0).getRoleCode(), sysUser.getOrgCode());
        return Result.OK(pageList);
    }


    @AutoLog(value = "体质监测表-添加")
    @ApiOperation(value = "体质监测表-添加", notes = "体质监测表-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SgHealthRecord hr) {
        SgMember member = this.sgMemberService.getOne(new QueryWrapper<SgMember>().eq("id", hr.getMemberId()));

        Calendar cal = Calendar.getInstance();

        // 获取当期年月日
        int thisYear = cal.get(Calendar.YEAR);
        int thisMonth = cal.get(Calendar.MONTH);
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

        if (member != null) {
            // 获取出生年月日
            cal.setTime(member.getBirthday());
            int birthYear = cal.get(Calendar.YEAR);
            int birthMonth = cal.get(Calendar.MONTH);
            int birthdayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

            int age = thisYear - birthYear;

            // 未足月
            if (thisMonth <= birthMonth) {
                // 当月
                if (thisMonth == birthMonth) {
                    // 未足日
                    if (dayOfMonth < birthdayOfMonth) {
                        age--;
                    }
                } else {
                    age--;
                }
            }

            // 男
            if (member.getSex() == 0) {
                // 18~39岁
                if (age >= 18 && age <= 39) {
                    if(hr.getBmi()!=null){
                        if (hr.getBmi() >= 5 && hr.getBmi() <= 10) {// 偏瘦
                            hr.setLevel(0);
                        }
                        if (hr.getBmi() >= 11 && hr.getBmi() <= 16) {// 标准（健康型）
                            hr.setLevel(1);
                        }
                        if (hr.getBmi() >= 17 && hr.getBmi() <= 21) {// 标准（警戒型）
                            hr.setLevel(2);
                        }
                        if (hr.getBmi() >= 22 && hr.getBmi() <= 26) {// 轻度肥胖
                            hr.setLevel(3);
                        }
                        if (hr.getBmi() >= 27 && hr.getBmi() <= 45) {// 重度肥胖
                            hr.setLevel(4);
                        }
                    }
                }

                // 40~59岁
                if (age >= 40 && age <= 59) {
                    if(hr.getBmi()!=null){
                        if (hr.getBmi() >= 5 && hr.getBmi() <= 11) {// 偏瘦
                            hr.setLevel(0);
                        }
                        if (hr.getBmi() >= 12 && hr.getBmi() <= 17) {// 标准（健康型）
                            hr.setLevel(1);
                        }
                        if (hr.getBmi() >= 18 && hr.getBmi() <= 22) {// 标准（警戒型）
                            hr.setLevel(2);
                        }
                        if (hr.getBmi() >= 23 && hr.getBmi() <= 27) {// 轻度肥胖
                            hr.setLevel(3);
                        }
                        if (hr.getBmi() >= 28 && hr.getBmi() <= 45) {// 重度肥胖
                            hr.setLevel(4);
                        }
                    }
                }

                // 60岁以上
                if (age >= 60) {
                    if(hr.getBmi()!=null){
                        if (hr.getBmi() >= 5 && hr.getBmi() <= 13) {// 偏瘦
                            hr.setLevel(0);
                        }
                        if (hr.getBmi() >= 14 && hr.getBmi() <= 19) {// 标准（健康型）
                            hr.setLevel(1);
                        }
                        if (hr.getBmi() >= 20 && hr.getBmi() <= 24) {// 标准（警戒型）
                            hr.setLevel(2);
                        }
                        if (hr.getBmi() >= 25 && hr.getBmi() <= 29) {// 轻度肥胖
                            hr.setLevel(3);
                        }
                        if (hr.getBmi() >= 30 && hr.getBmi() <= 45) {// 重度肥胖
                            hr.setLevel(4);
                        }
                    }
                }
            }

            // 女
            if (member.getSex() == 1) {
                // 18~39岁
                if (age >= 18 && age <= 39) {
                    if(hr.getBmi()!=null){
                        if (hr.getBmi() >= 5 && hr.getBmi() <= 20) {// 偏瘦
                            hr.setLevel(0);
                        }
                        if (hr.getBmi() >= 21 && hr.getBmi() <= 27) {// 标准（健康型）
                            hr.setLevel(1);
                        }
                        if (hr.getBmi() >= 28 && hr.getBmi() <= 34) {// 标准（警戒型）
                            hr.setLevel(2);
                        }
                        if (hr.getBmi() >= 35 && hr.getBmi() <= 39) {// 轻度肥胖
                            hr.setLevel(3);
                        }
                        if (hr.getBmi() >= 40 && hr.getBmi() <= 45) {// 重度肥胖
                            hr.setLevel(4);
                        }
                    }
                }

                // 40~59岁
                if (age >= 40 && age <= 59) {
                    if(hr.getBmi()!=null){
                        if (hr.getBmi() >= 5 && hr.getBmi() <= 21) {// 偏瘦
                            hr.setLevel(0);
                        }
                        if (hr.getBmi() >= 22 && hr.getBmi() <= 28) {// 标准（健康型）
                            hr.setLevel(1);
                        }
                        if (hr.getBmi() >= 29 && hr.getBmi() <= 35) {// 标准（警戒型）
                            hr.setLevel(2);
                        }
                        if (hr.getBmi() >= 36 && hr.getBmi() <= 40) {// 轻度肥胖
                            hr.setLevel(3);
                        }
                        if (hr.getBmi() >= 41 && hr.getBmi() <= 45) {// 重度肥胖
                            hr.setLevel(4);
                        }
                    }
                }

                // 60岁以上
                if (age >= 60) {
                    if(hr.getBmi()!=null){
                        if (hr.getBmi() >= 5 && hr.getBmi() <= 22) {// 偏瘦
                            hr.setLevel(0);
                        }
                        if (hr.getBmi() >= 23 && hr.getBmi() <= 29) {// 标准（健康型）
                            hr.setLevel(1);
                        }
                        if (hr.getBmi() >= 30 && hr.getBmi() <= 36) {// 标准（警戒型）
                            hr.setLevel(2);
                        }
                        if (hr.getBmi() >= 37 && hr.getBmi() <= 41) {// 轻度肥胖
                            hr.setLevel(3);
                        }
                        if (hr.getBmi() >= 42 && hr.getBmi() <= 45) {// 重度肥胖
                            hr.setLevel(4);
                        }
                    }
                }
            }
        }


        // 是否干预
        SgMember m = sgMemberService.getById(hr.getMemberId());
        if (m != null && m.getBodyfatMax() != null && m.getBodyfatMin() != null) {
            if(hr.getBmi()!= null){
                hr.setIntervene(hr.getBmi() >= m.getBodyfatMax() || hr.getBmi() <= m.getBodyfatMin() ? 0 : 1);
            }
        } else {
            hr.setIntervene(1);
        }
        // 级别：

        sgHealthRecordService.save(hr);
        return Result.OK("添加成功！");
    }


    @AutoLog(value = "体质监测表-编辑")
    @ApiOperation(value = "体质监测表-编辑", notes = "体质监测表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SgHealthRecord sgHealthRecord) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        sgHealthRecord.setInterveneTime(DateTime.now());
        sgHealthRecord.setInterveneUser(sysUser.getId());
        sgHealthRecord.setMemberName(null);
        sgHealthRecord.setMemberPhone(null);
        sgHealthRecord.setThreeTag(null);
        sgHealthRecord.setBodyfatWarning(null);
        sgHealthRecordService.updateById(sgHealthRecord);
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "体质监测表-通过id删除")
    @ApiOperation(value = "体质监测表-通过id删除", notes = "体质监测表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id") String id) {
        sgHealthRecordService.removeById(id);
        return Result.OK("删除成功!");
    }

    @AutoLog(value = "体质监测表-批量删除")
    @ApiOperation(value = "体质监测表-批量删除", notes = "体质监测表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids") String ids) {
        this.sgHealthRecordService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    @ApiOperation(value = "体质监测表-通过id查询", notes = "体质监测表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SgHealthRecord> queryById(@RequestParam(name = "id") String id) {
        SgHealthRecord sgHealthRecord = sgHealthRecordService.getById(id);
        if (sgHealthRecord == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgHealthRecord);
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SgHealthRecord sgHealthRecord) {
        return super.exportXls(request, sgHealthRecord, SgHealthRecord.class, "体质监测表");
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SgHealthRecord.class);
    }

    @ApiOperation(value = "查询居民血压测量记录列表", notes = "查询居民血压测量记录列表")
    @GetMapping(value = "/queryByMemberIdList")
    public Result<List<SgHealthRecord>> queryByMemberIdList(
            @RequestParam(name = "member_id") String member_id) {

        QueryWrapper<SgHealthRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", member_id);
        queryWrapper.orderByDesc("measuring_time");
//        IPage<SgBlutdruckRecord> pageList = sgBlutdruckRecordService.page(page, queryWrapper);
        List<SgHealthRecord> pageList = sgHealthRecordService.list(queryWrapper);
        if (pageList == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(pageList);
    }

}
